package com.sjb.cp.api.imageSearch.sub;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sjb.cp.api.imageSearch.model.ImageSearchResult;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author:sjb
 * @CreateTime:2025-01-26
 * @Description: 调用百度接口返回的 JSON 数据，提取出其中的图片列表并返回。
 * @Version：1.0
 */
@Slf4j
public class GetImageListApi {

    /**
     * 获取图片列表
     * @param searchUrl
     * @return
     */
    public static List<ImageSearchResult> getImageList(String searchUrl) {
        try {
            HttpResponse response = HttpUtil.createGet(searchUrl).execute();

            int status = response.getStatus();
            String body = response.body();

            if (status == 200){
                // 处理响应体
                return processResponse(body);
            }else {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"请求调用接口失败");
            }
        } catch (Exception e) {
            log.error("获取图片列表失败");
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取图片列表失败");
        }

    }


    /**
     * 处理响应体
     * @param responseBody
     * @return
     */
    private static List<ImageSearchResult> processResponse(String responseBody) {
        // 解析响应对象
        cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(responseBody);
        if (!jsonObject.containsKey("data")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未获取到图片列表");
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (!data.containsKey("list")) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未获取到图片列表");
        }
        JSONArray list = data.getJSONArray("list");
        return JSONUtil.toList(list, ImageSearchResult.class);
    }

    public static void main(String[] args) {
        String url = "https://graph.baidu.com/ajax/pcsimi?carousel=503&entrance=GENERAL&extUiData%5BisLogoShow%5D=1&inspire=general_pc&limit=30&next=2&render_type=card&session_id=16250747570487381669&sign=1265ce97cd54acd88139901733452612&tk=4caaa&tpl_from=pc";
        List<ImageSearchResult> imageList = getImageList(url);
        System.out.println("搜索成功" + imageList);
    }

}
